'''
@auther tianxiaoxi  
@file connect_tools by
@time 2021/12/21 11:16

用于连接数据  数据库,
'''
# 导包
import pymysql


class DBUtil():
    # 初始化
    __conn = None
    __cursor = None

    # 建立连接
    @classmethod
    def __get_connect(cls):
        if cls.__conn is None:
            cls.__conn = pymysql.connect(port=3306,
                                         host='localhost',
                                         user='root',
                                         password='root',
                                         database='books')
        return cls.__conn

    # 建立游标
    @classmethod
    def __get_cursor(cls):

        if cls.__cursor is None:
            conn = cls.__get_connect()
            cursor = conn.cursor()
        return cursor

    # 执行sql
    @classmethod
    def exe_sql(cls, sql):
        try:

            # cursor = cls.__get_corsor()
            # if sql.split()[1].lower() == 'select':
            #     result = cls.__cursor.execute(sql)
            #     return result
            # else:
            #     result = cls.__cursor.execute(sql)
            #     cls.__conn.commit()
            #     return result

            # 获取游标
            cursor = cls.__get_cursor()
            # 执行sql
            cursor.execute(sql)

            # 如果是查询
            if sql.split()[0].lower() == 'select':
                # 返回所有数据
                return cursor.fetchall()
            else:
                # 提交事务
                cls.__conn.commit()
                # 返回受影响的结果行数
                return cursor.rowcount

        except Exception as e:
            print(e)
            cls.__conn.rollback()

        finally:
            cls.__close_cursor()
            cls.__close_connect()

    # 关闭游标
    @classmethod
    def __close_cursor(cls):
        if cls.__cursor:
            cls.__cursor.close()
            cls.__cursor = None

    @classmethod
    def __close_connect(cls):
        if cls.__conn:
            cls.__conn.close()
            cls.__conn = None
